package com.qs.javame.thread.join;

/**
 * 测试：自定义实现线程B总是在线程A执行完成后执行
 */
public class TestJoin3 {
    public static void main(String[] args) {
        ThreadA threadA = new ThreadA();
        ThreadB threadB = new ThreadB(threadA);

        threadA.start();
        threadB.start();
    }


    static class ThreadA extends Thread {

        public void myJoin() throws InterruptedException {
            while (isAlive()) {
                this.wait();
            }
        }

        @Override
        public void run() {
            synchronized (this) {
                System.out.println(Thread.currentThread().getName() + "-执行TaskA的run()~");
                this.notify();
            }
        }
    }


    static class ThreadB extends Thread {

        private ThreadA thread;

        public ThreadB(ThreadA thread) {
            this.thread = thread;
        }

        @Override
        public void run() {
            synchronized (thread) {
                try {
                    //等待线程A执行完
                    thread.myJoin();

                    //这里真正开始执行ThreadB的线程任务
                    System.out.println(Thread.currentThread().getName() + "-执行TaskB的run()~");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println(Thread.currentThread().getName() + "-发生中断，中断：" + Thread.currentThread().isInterrupted());
                }
            }
        }
    }

}
